<style lang="less">
.locate-blk {
  position: relative;
  .locate-map {
    color: #333;
  }
  .unit-search {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 10;
    width: 40%;
    .el-input__inner {
      border: 1px solid #0f71e2;
      border-right: none;
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
      &:hover {
        border-color: #0f71e2;
      }
    }
  }
  .search-result {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 10;
    width: 280px;
    max-height: 380px;
    overflow: auto;
  }
  .amap-content-body {
    color: #333;
  }
}
</style>
<template>
  <div class="locate-blk">
    <div class="unit-search flex">
      <el-input
        id="addrInput"
        class="flex-1"
        placeholder="请输入"
        v-model.trim="addr"
      ></el-input>
      <el-button type="primary" @click="searchAddr">搜索</el-button>
    </div>
    <div id="searchResult" class="search-result"></div>
    <div id="locateMap" class="locate-map"></div>
    <div class="text-right mt-10">
      <el-button type="primary" @click="submitAction">提交</el-button>
    </div>
  </div>
</template>
<script>
import AMap from "AMap";
let map = null;
let marker = null;
let district = null;
let placeSearch = null;
let selectedCoord = "";
export default {
  name: "Location",
  props: {
    coord: {
      type: String,
      default: "",
    },
    area: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "",
    },
    areaNames: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  computed: {},
  watch: {},
  data() {
    return {
      addr: "",
    };
  },
  methods: {
    searchAddr() {
      if (marker != null) {
        map.remove(marker);
      }
      //关键字查询
      placeSearch.search(this.addr);
    },
    initMap() {
      map = new AMap.Map("locateMap", {
        resizeEnable: true,
        zoom: 14,
      });
      let currentCity = "";
      if (this.area) {
        const temp = this.area.split(",");
        currentCity = temp[2];
      } else {
        currentCity =
          this.areaNames.length > 1 ? this.areaNames[1] : this.areaNames[0];
      }

      map.on("click", (e) => {
        this.createMarker(e.lnglat.getLng(), e.lnglat.getLat());
      });

      if (this.coord) {
        let coord = this.coord.split(",");
        this.createMarker(coord[0], coord[1]);
        map.setFitView(null, false, [160, 160, 160, 160]); //视图自适应
      } else {
        let addr = this.area
          ? this.area.replace(",", "")
          : this.areaNames.toString().replace(",", "");
        const geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all",
        });
        geocoder.getLocation(addr, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            // 获取经纬度
            map.setCenter(result.geocodes[0].location);
          }
        });
      }

      AMap.plugin(["AMap.PlaceSearch"], () => {
        var autoOptions = {
          // 城市，默认全国
          city: currentCity,
          //city: "金华市",
          // 使用联想输入的input的id
          input: "addrInput",
        };
        // var autocomplete = new AMap.AutoComplete(autoOptions);

        placeSearch = new AMap.PlaceSearch({
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: currentCity, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          map: map, // 展现结果的地图实例
          panel: "searchResult", // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        placeSearch.on("markerClick", (e) => {
          if (marker != null) {
            map.remove(marker);
          }
          selectedCoord = e.data.location.lng + "," + e.data.location.lat;
        });

        placeSearch.on("listElementClick", (e) => {
          if (marker != null) {
            map.remove(marker);
          }
          selectedCoord = e.data.location.lng + "," + e.data.location.lat;
        });
        // autocomplete.on("select", (e) => {
        //   placeSearch.search(e.poi.name);
        // });
      });
    },
    drawBounds() {
      let polygons = [];
      //加载行政区划插件
      if (!district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 0, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };
        district = new AMap.DistrictSearch(opts);
      }
      // 行政区查询
      district.search(this.areaNames[2], (status, result) => {
        map.remove(polygons); //清除上次结果
        polygons = [];
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: "#80d8ff",
              strokeColor: "#0091ea",
            });
            polygon.on("click", (e) => {
              this.createMarker(e.lnglat.getLng(), e.lnglat.getLat());
            });
            polygons.push(polygon);
          }
        }
        map.add(polygons);
        map.setFitView(polygons); //视口自适应
      });
    },
    createMarker(lng, lat) {
      if (marker != null) {
        map.remove(marker);
      }
      marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
      });
      map.add(marker);
      selectedCoord = lng + "," + lat;
    },
    submitAction() {
      this.$emit("save", selectedCoord.split(","));
    },
  },
  mounted() {
    this.initMap();
  },
  destroyed() {
    //
  },
};
</script>
<style lang="less" scoped>
.locate-map {
  width: 100%;
  height: 400px;
}
</style>
